package com.joysuch.wwyt.mh;

import lombok.extern.log4j.Log4j2;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Log4j2
public class GZIPUtil {

    /**
     * 递归压缩文件
     *
     * @param output    ZipOutputStream 对象流
     * @param file      压缩的目标文件流
     * @param childPath 条目目录
     */
    private static void zip(ZipOutputStream output, File file, String childPath) {
        FileInputStream input = null;
        try {
            if (file.isDirectory()) {
                File[] list = file.listFiles();
                childPath = childPath + (childPath.length() == 0 ? "" : "/") + file.getName();
                for (File f : list) {
                    zip(output, f, childPath);
                }
            } else {
                childPath = (childPath.length() == 0 ? "" : childPath + "/") + file.getName();
                output.putNextEntry(new ZipEntry(childPath));
                input = new FileInputStream(file);
                int readLen;
                byte[] buffer = new byte[1024 * 8];
                while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) {
                    output.write(buffer, 0, readLen);
                }
            }
        } catch (Exception ex) {
            log.error("Failed to compress file error :", ex);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException ex) {
                    log.error("Compress file close FileInputStream error :", ex);
                }
            }
        }
    }

    /**
     * 压缩文件（文件夹）
     *
     * @param path   目标文件流
     * @param format zip 格式 | rar 格式
     * @throws Exception
     */
    public static String zipFile(File path, String format) throws Exception {
        String generatePath;
        if (path.isDirectory()) {
            generatePath = !path.getParent().endsWith("/") ? path.getParent() + File.separator + path.getName() + "." + format : path.getParent() + path.getName() + "." + format;
        } else {
            generatePath = !path.getParent().endsWith("/") ? path.getParent() + File.separator : path.getParent();
            generatePath += path.getName().substring(0, path.getName().lastIndexOf(".")) + "." + format;
        }
        // 输出流
        FileOutputStream outputStream = new FileOutputStream(generatePath);
        // 压缩输出流
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream));
        zip(out, path, "");
        out.flush();
        out.close();
        return generatePath;
    }
}
